package xyz.zq.sf.common.security.component;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.HttpStatus;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.stereotype.Component;
import xyz.zq.sf.common.core.exception.DeniedException;
import xyz.zq.sf.common.core.util.R;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 授权拒绝处理器，覆盖默认的OAuth2AccessDeniedHandler 包装失败信息到DeniedException
 *
 * @author hzq
 * @date 2021-01-30 16:45
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class OAuth2AccessResourceDeniedHandler extends OAuth2AccessDeniedHandler {

    private final ObjectMapper objectMapper;

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException authException) throws IOException, ServletException {
        log.info("授权失败,禁止访问:{}", request.getRequestURI());
        response.setStatus(HttpStatus.HTTP_FORBIDDEN);
        response.setCharacterEncoding(CharsetUtil.UTF_8);
        response.setContentType(ContentType.JSON.toString(CharsetUtil.CHARSET_UTF_8));
        R<DeniedException> r = R.failed(new DeniedException("授权失败，禁止访问"));
        PrintWriter writer = response.getWriter();
        writer.append(objectMapper.writeValueAsString(r));
    }
}
